package com.cwx.mychat.login.authentication.phone;

import com.cwx.mychat.entity.dto.PhoneLoginUserDto;
import com.cwx.mychat.login.exception.CheckoutException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * 作者： cwx
 * 时间： 2024/11/26 18:25
 * 版本： 1.0
 * 注释：
 */
@Slf4j
public class PhoneAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public PhoneAuthenticationFilter(AntPathRequestMatcher pathRequestMatcher, //登录url
                                     AuthenticationManager authenticationManager, //核心认证校验器
                                     AuthenticationSuccessHandler authenticationSuccessHandler, //登录成功逻辑
                                     AuthenticationFailureHandler authenticationFailureHandler) { //登录失败逻辑
        super(pathRequestMatcher);
        log.info("获取到url = {}", pathRequestMatcher.getPattern());
        setAuthenticationManager(authenticationManager);
        setAuthenticationSuccessHandler(authenticationSuccessHandler);
        setAuthenticationFailureHandler(authenticationFailureHandler);
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        try{
            //提取数据
            String requestJsonData = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            ObjectMapper objectMapper = new ObjectMapper();
            PhoneLoginUserDto phoneLoginUserDto = objectMapper.readValue(requestJsonData, PhoneLoginUserDto.class);
            String password = phoneLoginUserDto.getPassword();
            String emailOrPhone = phoneLoginUserDto.getEmailOrPhone();
            //封装成Spring Security需要的对象
            PhoneAuthentication phoneAuthentication = new PhoneAuthentication();
            phoneAuthentication.setPhoneOrEmail(emailOrPhone);
            phoneAuthentication.setPassword(password);
            phoneAuthentication.setAuthenticated(false);
            //开始登录认证
            log.info("开始登录验证：emailOrPhone为{}, 密码为{}", emailOrPhone, password);
            return getAuthenticationManager().authenticate(phoneAuthentication);
        }catch (Exception e){
            log.error("提取数据产生异常", e);
            throw new CheckoutException(e.getMessage());
        }
    }
}
